﻿using AuthCenter.Application;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.Reflection;
using System.Text;

namespace AuthCenter.Api.Write.Extensions
{
    public static  class ServiceCollectionExtensions
    {
        /// <summary>
        /// 依赖注入扩展类
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddServices(this IServiceCollection services) 
        {
            //注册仓储
            services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));
            //注册中介者
            services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblies(Assembly.GetExecutingAssembly()));
            //注册AutoMapper
            services.AddAutoMapper(p =>
            {
                p.AddProfile<AutoMapperFail>();
            });
            return services;
        }
        /// <summary>
        /// 注册数据库
        /// </summary>
        /// <typeparam name="TDbContext"></typeparam>
        /// <param name="service"></param>
        /// <param name="connectionString"></param>
        /// <param name="enableSqllog">是否打印执行EF语句转译的sql</param>
        /// <returns></returns>
        public static IServiceCollection AddDbContextService<TDbContext>(this IServiceCollection service, string? connectionString, bool enableSqllog) where TDbContext : DbContext 
        {
            return service.AddDbContext<TDbContext>(builder => 
            {
                builder.UseSqlServer(connectionString
                //    , action =>
                //{
                //    action.EnableRetryOnFailure
                //    (maxRetryCount: 10,
                //    maxRetryDelay: TimeSpan.FromSeconds(60),
                //    errorNumbersToAdd: null
                //    );
                //}
                )
                .EnableSensitiveDataLogging();
                if (enableSqllog) 
                {
                    builder.UseLoggerFactory(LoggerFactory.Create(configure =>
                    {
                        configure.AddFilter((category, level) => category == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information)
                        .AddConsole();
                    }));
                }
            });
        }

        /// <summary>
        /// 注册JWT
        /// </summary>
        /// <param name="collection"></param>
        /// <param name="builder"></param>

        public static void AddJWT(this IServiceCollection collection, WebApplicationBuilder builder) 
        {
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
            {
                var secreByte = Encoding.UTF8.GetBytes(builder.Configuration["Authorization:SecretKey"]);
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    //验证发布者
                    ValidateIssuer = true,
                    ValidIssuer = builder.Configuration["Authorization:Issuer"],
                    //验证接收者
                    ValidateAudience = true,
                    ValidAudience = builder.Configuration["Authorization:Audience"],
                    //验证是否过期
                    ValidateLifetime = true,
                    IssuerSigningKey = new SymmetricSecurityKey(secreByte)
                };
            });
        }
    }
}
